package com.jiuzhou.surery.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfigration {
    
    
    private final SurveyUserDetailsManager userDetailsManager;

        public SecurityConfigration(SurveyUserDetailsManager userDetailsManager) {
            this.userDetailsManager = userDetailsManager;
        }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/javascripts/**", "/css/**","/images/**", "/img/**","/error","/login","/user/dashboard").permitAll()
                .requestMatchers("/h2-console/**").permitAll()
                .requestMatchers("/items/**","/files/**").hasAuthority("USER")
                .requestMatchers("/admin/**").hasAuthority("ADMIN")
                
                .anyRequest().denyAll()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/items/add", true)
                .permitAll()
            )
            .logout((logout) -> logout.permitAll())
            .csrf(csrf -> csrf
                .ignoringRequestMatchers("/files/upload")
                .ignoringRequestMatchers("/h2-console/**")
            )
            .headers(headers -> headers
                .contentSecurityPolicy("frame-ancestors 'self'")
            );
        return http.build();
    }


    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        var authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
       authenticationManagerBuilder.userDetailsService(userDetailsManager);
       return authenticationManagerBuilder.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
